﻿using ProtoBuf.Message;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yunchang;
using Yunchang.NetworkLayer;
using Yunchang.Scene;
namespace AutoChess
{
    public enum ACMainPagePanelType
    {
        None,
        Shop,
        ChessInfo,
        ProfitInfo,
        BuffInfo,
        PlayerListInfo,
        OtherCover
    }

    public class AutoChessMainPage : Page
    {
        public PlayerInfoListPanel playerListInfo;//玩家列表
        public PlayerInfoPanel playerInfo;//角色属性信息
        public RoundStatePanel stateInfo; //回合信息

        // 可打开关闭panel
        public ShipGridPanel shopGridInfo;//商店面板
        public ACGroupPanel groupInfo;//Buff信息面板
        public ACChessInfoPanel chessInfo;//棋子信息
        public ProfitDescPanel profitDescInfo;//预计收益信息

        public GameObject leaveBtn;
        public GameObject sellBtn;
        public TweenerCtrl tweeCtr;
        public Text levelText;
        public Text sellText;

        public Transform coinPos, uiEffectRoot;

        public Transform lvUpBtnTrans,lvUpHpTrans;

        private ACMainPagePanelType curPanel = ACMainPagePanelType.None;
        private long curPlayerGuid;
        #region msg

        private void RegisterMsg()
        {
            EventManager.AddEventListener<long>(CommonEvent.SWITCH_AUTO_CHESS_PLAYER, SwitchOnePlayer); //切换当前的玩家信息
            EventManager.AddEventListener<long>(CommonEvent.UPDATE_PLAYER_INFO, UpdatePlayerInfo);       //当前的玩家属性信息更新的时候
            EventManager.AddEventListener<GridType>(CommonEvent.ON_GAMEFIELD_CHESS_UPDATE, OnInBattleChessUpdate);//战场棋子刷新
            EventManager.AddEventListener<AutoChessStateType>(CommonEvent.ON_STATE_TO_CHANGE_BY_SERVER, OnStateToAdjust); //进入调整阶段的时候
            EventManager.AddEventListener<int>(CommonEvent.ON_AC_CHECK_CHESS_INFO, OnCheckChessInfo);      //点击查看棋子信息
            EventManager.AddEventListener<bool>(CommonEvent.ON_SET_SHIP_GRID_PANEL, SetShopPanelState);   //设置商店面板开关
            EventManager.AddEventListener<ACGrid>(CommonEvent.ON_AUTOCHESS_SELECT_UNIT, OnSelectChess);      //点击查看棋子信息
            EventManager.AddEventListener<SCAutoChessGoldIncome>(CommonEvent.ON_AUTOCHESSS_INCOME, OnIncomeMsg);
            EventManager.AddEventListener<CommonEffectResId>(CommonEvent.ON_PLAY_UI_EFFECT, OnPlayerUIEffect);
            EventManager.AddEventListener<AutoChessModeState>(CommonEvent.ON_AUTOCHESS_STATE_UPDATE, OnStateUpdate);
            EventManager.AddEventListener<bool>(CommonEvent.ON_SHIP_LEVEL_UPGRADES, OnShipLvUp);
            EventManager.AddEventListener<ACPlayerData>(CommonEvent.ON_SHIP_MULITY_KILL, OnMulityKill);
            EventManager.AddEventListener<HeroAppearMsg, string>(CommonEvent.ON_SHIP_STAR_UP, OnPlayerStarUp);
            EventManager.AddEventListener(CommonEvent.ON_PLAYER_LIST_CHANGE,OnPlayerListChange);
            EventManager.AddEventListener(CommonEvent.ON_CLICK_BACK_PANEL,OnClickBackgroudPanel);
            EventManager.AddEventListener<long>(CommonEvent.ON_Refresh_Ship_HP_UI, OnRefreshUIHP);
            EventManager.AddEventListener(CommonEvent.ON_PlayEffect_Meteor, OnPlayEffectMeteor);
            NetworkDriver.Instance.RegistSocketHandler(OpDefine.SCAutoChessUpgradeShip, OnSCAutoChessUpgradeShip); //更新船的属性

            //发送消息给渲染管理器，将商店格子的渲染器绑定到UI上
            EventManager.TriggerEvent<bool, List<GameObject>>(CommonEvent.PUSH_SHOP_GRID_ROOT, true, shopGridInfo.shipGridRoot);
        }

        private void UnRegisterMsg()
        {
            EventManager.RemoveEventListener<long>(CommonEvent.SWITCH_AUTO_CHESS_PLAYER, SwitchOnePlayer);
            EventManager.RemoveEventListener<long>(CommonEvent.UPDATE_PLAYER_INFO, UpdatePlayerInfo);//当前的玩家信息
            EventManager.RemoveEventListener<GridType>(CommonEvent.ON_GAMEFIELD_CHESS_UPDATE, OnInBattleChessUpdate);
            EventManager.RemoveEventListener<AutoChessStateType>(CommonEvent.ON_STATE_TO_CHANGE_BY_SERVER, OnStateToAdjust);
            EventManager.RemoveEventListener<int>(CommonEvent.ON_AC_CHECK_CHESS_INFO, OnCheckChessInfo);
            EventManager.RemoveEventListener<bool>(CommonEvent.ON_SET_SHIP_GRID_PANEL, SetShopPanelState);
            EventManager.RemoveEventListener<ACGrid>(CommonEvent.ON_AUTOCHESS_SELECT_UNIT, OnSelectChess);
            EventManager.RemoveEventListener<SCAutoChessGoldIncome>(CommonEvent.ON_AUTOCHESSS_INCOME, OnIncomeMsg);
            EventManager.RemoveEventListener<CommonEffectResId>(CommonEvent.ON_PLAY_UI_EFFECT, OnPlayerUIEffect);
            EventManager.RemoveEventListener<AutoChessModeState>(CommonEvent.ON_AUTOCHESS_STATE_UPDATE, OnStateUpdate);
            EventManager.RemoveEventListener<bool>(CommonEvent.ON_SHIP_LEVEL_UPGRADES, OnShipLvUp);
            EventManager.RemoveEventListener<ACPlayerData>(CommonEvent.ON_SHIP_MULITY_KILL, OnMulityKill);
            EventManager.RemoveEventListener<HeroAppearMsg, string>(CommonEvent.ON_SHIP_STAR_UP, OnPlayerStarUp);
            EventManager.RemoveEventListener(CommonEvent.ON_PLAYER_LIST_CHANGE, OnPlayerListChange);
            EventManager.RemoveEventListener(CommonEvent.ON_CLICK_BACK_PANEL, OnClickBackgroudPanel);
            EventManager.RemoveEventListener<long>(CommonEvent.ON_Refresh_Ship_HP_UI, OnRefreshUIHP);
            EventManager.RemoveEventListener(CommonEvent.ON_PlayEffect_Meteor, OnPlayEffectMeteor);
            NetworkDriver.Instance.UnregisterSocketHandler(OpDefine.SCAutoChessUpgradeShip, OnSCAutoChessUpgradeShip);

            //发送消息给渲染管理器，将商店格子的渲染器 还原到管理器里
            EventManager.TriggerEvent<bool, List<GameObject>>(CommonEvent.PUSH_SHOP_GRID_ROOT, false, shopGridInfo.shipGridRoot);
        }
        private void OnPlayEffectMeteor()
        {
            var endscreenPos = RectTransformUtility.WorldToScreenPoint(CameraTools.Instance._uiCamera, coinPos.position);
            Vector2 endPos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.GetComponent<RectTransform>(), endscreenPos, CameraTools.Instance._uiCamera, out endPos);
            MeteorEffect.GenMeteorEffect(transform, new Vector3(0, 100, 0), endPos, new Vector3(300, 0, 0));
        }
        private void OnRefreshUIHP(long playerGuid)
        {
            if (playerGuid == AutoChessManager.Ins.cacheData.CurPlayerData.GUID)
            {
                playerInfo.RefreshPlayerHP(AutoChessManager.Ins.cacheData.CurPlayerData);
            }
        }
        private void OnClickBackgroudPanel()
        {
            playerListInfo.ClosePanel();
        }
        //刷新玩家列表排名
        private void OnPlayerListChange()
        {
            playerListInfo.RefreshRank();
        }
        private void OnPlayerUIEffect(CommonEffectResId effectId)
        {
            CommonEffectManager.Instance.PlayEffectImmediate(effectId, uiEffectRoot);
        }
        private void OnIncomeMsg(SCAutoChessGoldIncome msg)
        {
            shopGridInfo.CloseShop();
            var list = new List<string>();
            list.Add("+" + msg.baseGold);
            list.Add("+" + msg.Interest);
            list.Add("+" + msg.winGold);
            list.Add("+" + msg.seriesWin);
            list.Add("+" + msg.seriesLose);
            var data = new ACResultTipData();
            data.result = list;
            data.round = string.Format(TableTextBlo.GetText("ACFightRecordWave"), AutoChessManager.Ins.cacheData.RoundNum);
            MessageBoxManager.Instance.CreateAutoChessResultTip(data);

            var endscreenPos = RectTransformUtility.WorldToScreenPoint(CameraTools.Instance._uiCamera, coinPos.position);
            Vector2 endPos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.GetComponent<RectTransform>(), endscreenPos, CameraTools.Instance._uiCamera, out endPos);
            MeteorEffect.GenMeteorEffect(transform, new Vector3(0, 100, 0), endPos, new Vector3(300, 0, 0));
            UtilityHelper.PlayUIAudio("AC_round");
        }

        //自己升级
        private void OnSCAutoChessUpgradeShip(object msg)
        {
        }
        #endregion

        protected override void DoOpen()
        {
            base.DoOpen();
            RegisterMsg();

            Yunchang.EventManager.TriggerEvent<long>(CommonEvent.UPDATE_PLAYER_INFO, AutoChessPlayerCtr.Ins.CurrentPlayer.playerGuid);
            if (AutoChessManager.Ins.cacheData.ServerDataState != AutoChessStateType.AUTO_CHESS_STATE_CLOSED)
            {
                tweeCtr.PlayForward();

                AutoChessFieldViewCtr.Ins.ActionCtr.StartActionQueue(ActionQueueType.AdjustStart, null);

                AutoChessPlayerCtr.Ins.CurrentPlayer.RefreshHeroNumberState();
            }
            playerListInfo.InitPanel();//初始化玩家列表
            EventManager.TriggerEvent(CommonEvent.ON_Refresh_Ship_HP_UI, AutoChessManager.Ins.cacheData.CurPlayerData.GUID);
        }

        protected override void DoClose(bool immediately)
        {
            base.DoClose(immediately);
            UnRegisterMsg();
        }

        #region event
        private void SetShopPanelState(bool open)
        {
            if (open)
            {
                if (!AutoChessManager.Ins.cacheData.CurPlayerData.IsSeeSelf ||
                    AutoChessManager.Ins.cacheData.CurPlayerData.IsDeath)
                    return;
                ClickAddHero();
            }
            else
            {
                shopGridInfo.CloseShop();
                chessInfo.Close();
            }
        }

        //回合更新时候的回调 调整回合开始更新下预计收益栏，波数等。 进入调整阶段
        private void OnStateToAdjust(AutoChessStateType state)
        {
            if (state == AutoChessStateType.AUTO_CHESS_STATE_ADJUST || state == AutoChessStateType.AUTO_CHESS_STATE_FIGHTING)
            {
                stateInfo.RefreshState(); //刷新回合信息
            }
            else if (state == AutoChessStateType.AUTO_CHESS_STATE_CLOSED)
            {
                shopGridInfo.CloseShop();
            }
        }

        private void OnCheckChessInfo(int chessId)
        {
            chessInfo.SetData(chessId);
            SwitchCurPanel(ACMainPagePanelType.ChessInfo);
        }

        // 点击格子的时候
        private void OnSelectChess(ACGrid gridUnit)
        {
            profitDescInfo.Close();
            groupInfo.Close();
            if (gridUnit == null || gridUnit.heroUnit == null || gridUnit.GridType == GridType.ShopGrid)
            {
                chessInfo.Close();
            }

            if (gridUnit == null || gridUnit.heroUnit == null || gridUnit.GridType == GridType.ShopGrid || !AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer)
            {
                sellBtn.SetActive(false);
            }
            else
            {
                if (AutoChessManager.Ins.GetCurrentStateType() == AutoChessModeState.ShowFightState && gridUnit.GridType != GridType.PreChooseGrid)
                {
                    // do nothing
                }
                else
                {
                    sellBtn.SetActive(true);
                    var tableChess = Table.Blo.AutoChessBlo.GetChessTable(gridUnit.heroUnit.ChessID);
                    sellText.text = "+" + tableChess.sellPrice;
                }
            }
        }

        private void UpdatePlayerInfo(long guid)
        {
            curPlayerGuid = guid;
            var player = AutoChessManager.Ins.cacheData.GetPlayerData(guid);
            playerInfo.RefreshAllPlayerInfo(player);//玩家界面信息
            stateInfo.RefreshState();               //刷新回合信息
            profitDescInfo.RefreshUI(player);       //刷新预计收益
            RefreshGroupInfo();

            var self = AutoChessManager.Ins.cacheData.GetSelfPlayerData();
            if (self.IsDeath) //已经死亡返回
            {
                leaveBtn.SetActive(true);
                levelText.text = TableTextBlo.GetText("ChessFieldLeaveBtnText");
                return;
            }
            leaveBtn.SetActive(!player.IsSeeSelf); //看自己返回，看别人隐藏
            levelText.text = TableTextBlo.GetText("ChessFieldReturnBtnText");
            sellBtn.gameObject.SetActive(false);
        }
        /// <summary>
        /// 将所有信息刷新一次
        /// </summary>
        /// <param name="guid"></param>
        private void SwitchOnePlayer(long guid)
        {
            UpdatePlayerInfo(guid);
            if (AutoChessManager.Ins.cacheData.ServerDataState != AutoChessStateType.AUTO_CHESS_STATE_FIGHTING)
            {
                EventManager.TriggerEvent(CommonEvent.ON_Refresh_Ship_HP_UI, guid);
            }
        }

        //战斗场地的棋子发生变化 刷新buf显示
        private void OnInBattleChessUpdate(GridType gridType)
        {
            shopGridInfo.RefreshHeroItems();
            playerInfo.RefreshFightHeroNumber(AutoChessManager.Ins.cacheData.GetCurFieldPlayerData());

            RefreshGroupInfo();
        }

        private void RefreshGroupInfo()
        {
            // 阵营属性
            List<int> herosInBattleField = new List<int>();
            foreach (var item in AutoChessPlayerCtr.Ins.CurrentPlayer.HeroUnits)
            {
                if (item.MapGrid != null && item.MapGrid.GridType == GridType.FightGrid)
                    herosInBattleField.Add(item.HeroID);
            }
            groupInfo.SetData(herosInBattleField);
        }

        private void OnStateUpdate(AutoChessModeState stateType)
        {
            if (stateType == AutoChessModeState.ShowFightState)
            {
                sellBtn.SetActive(false);
            }
        }

        private void OnShipLvUp(bool isUpgrade)
        {
            CommonEffectManager.Instance.PlayEffectImmediate(isUpgrade ? CommonEffectResId.AC_150_zizhouqi_EXPShengji : CommonEffectResId.AC_150_zizhouqi_EXP, lvUpBtnTrans);
            if (isUpgrade)
            {
                CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_UI_150_zizhouqi_LVshengji, lvUpHpTrans);
            }
        }

        private void OnMulityKill(ACPlayerData data)
        {
            int seriesWin = data.SeriesWin;
            if (seriesWin == 3 || seriesWin == 5 || seriesWin == 10)
            {
                CommonEffectManager.Instance.PlayEffectQueue(CommonEffectResId.AC_UI_AutoChess_MulityKill, UI.UIEffectManager.Instance.transform, (obj) =>
                {
                    if (obj != null)
                    {
                        obj.GetComponent<UI.UFMultiKillEffect>().SetEffectInfo(data);
                    }
                });
            }
        }

        private void OnPlayerStarUp(HeroAppearMsg msg, string playerName)
        {
            if(msg.opType == AutoChessOpType.AUTO_CHESS_OP_STAR_GROWTH)
            {
                int chessId = msg.heroData.chessId;
                var dict = Table.Blo.AutoChessBlo.GetChessTable(chessId);
                var hero = Table.Blo.TableHeroBlo.GetTableHero(dict.heroId);

                var sb = new System.Text.StringBuilder();
                sb.Append(playerName);
                sb.Append(":");
                sb.Append(hero.heroName);
                for(int i = 0; i < dict.star; i++)
                {
                    sb.Append("<sprite=9>");
                }
                DisplayBullet(sb.ToString());
            }
        }

        public void DisplayBullet(string content)
        {
            BulletManager.Instance.DisplayBullet(content, BulletScreen.ColorType.Yellow, false, false);
        }

#endregion

        #region Btn
       
        public void ReturnOrLeave()
        {
            var player = AutoChessManager.Ins.cacheData.GetPlayerData(curPlayerGuid);
            //if (player.IsDeath)//退出
            //{
            //    MessageBoxManager.Instance.CreateMessageBox(MessageBoxManager.MessageBoxType.MessageBox, TableTextBlo.GetText("Tip"), TableTextBlo.GetText("ChessLeaveContent"), (result) =>
            //    {
            //        if (result == 1)
            //        {
            //            AutoChessManager.Ins.SendCSAutoChessPlayerQuit();
            //            //TODO 打开结算面板
            //        }
            //    });
            //}
            //else //没死亡就是返回到自己
            {
                AutoChessManager.Ins.SwitchToPlayer(StaticData.playerData.playerId);
            }
        }
        //请求退出
        public void Exist()
        {
            MessageBoxManager.Instance.CreateMessageBox(MessageBoxManager.MessageBoxType.MessageBox, TableTextBlo.GetText("Tip"), TableTextBlo.GetText("AutoChessExit"),
                (result) =>
                {
                    if (result == 1)
                        AutoChessManager.Ins.SendCSAutoChessPlayerQuit();
                }, true, BoxType.TwoButtom);
        }

        public void ClickBottumShow()
        {

        }
        public void ClickVoice()
        {
            PageManager.Instance.OpenPage("UIChannelPage", new ChannelChatPageParam() { chatType = ChatType.Chanel_AutoChess, isCloseCameraTween = false });
            SwitchCurPanel(ACMainPagePanelType.OtherCover);
        }
        public void ClickPlayerList()
        {
            PageManager.Instance.OpenPage("AutoChessPlayerListPage");
            SwitchCurPanel(ACMainPagePanelType.OtherCover);
        }
        /// <summary>
        /// 点击升级
        /// </summary>
        public void ClickLevelUp()
        {
            AutoChessManager.Ins.SendUpgradeShipBlock();
        }

        //说明
        public void ClickDesc()
        {
            PageManager.Instance.OpenPage("Chess_ExplainPage");
            SwitchCurPanel(ACMainPagePanelType.OtherCover);
        }

        //商店
        public void ClickAddHero()
        {
            shopGridInfo.OpenShop();
            SwitchCurPanel(ACMainPagePanelType.Shop);
        }

        public void OnSellBtn()
        {
            if (AutoChessMapMgr.Ins.CurSelectGrid != null)
            {
                AutoChessManager.Ins.SendSellChess(AutoChessMapMgr.Ins.CurSelectGrid.ServerIndex);
            }
        }

        //战斗记录
        public void OnClickFightRecordBtn()
        {
            PageManager.Instance.OpenPage("ChessFightRecordPage");
            SwitchCurPanel(ACMainPagePanelType.OtherCover);
        }

        public void OnClickProbability()
        {
            PageManager.Instance.OpenPage("AutoChessProbability");
        }

        public void SwitchCurPanel(ACMainPagePanelType panel)
        {
            curPanel = panel;
            switch (curPanel)
            {
                case ACMainPagePanelType.None:
                    break;
                case ACMainPagePanelType.Shop:
                    {
                        playerListInfo.ClosePanel();
                        //shopGridInfo.OpenShop();
                        groupInfo.DetailPanel.Close();
                        chessInfo.Close();
                        profitDescInfo.Close();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
                case ACMainPagePanelType.ChessInfo:
                    {
                        shopGridInfo.CloseShop();
                        groupInfo.DetailPanel.Close();
                        //chessInfo.Close();
                        profitDescInfo.Close();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
                case ACMainPagePanelType.ProfitInfo:
                    {
                        shopGridInfo.CloseShop();
                        groupInfo.DetailPanel.Close();
                        chessInfo.Close();
                        //profitDescInfo.ClickUIUp();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
                case ACMainPagePanelType.BuffInfo:
                    {
                        shopGridInfo.CloseShop();
                        //groupInfo.DetailPanel.Close();
                        chessInfo.Close();
                        profitDescInfo.Close();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
                case ACMainPagePanelType.PlayerListInfo:
                    {
                        shopGridInfo.CloseShop();

                        groupInfo.DetailPanel.Close();
                        groupInfo.Close();

                        chessInfo.Close();
                        profitDescInfo.Close();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
                case ACMainPagePanelType.OtherCover:
                    {
                        shopGridInfo.CloseShop();
                        groupInfo.DetailPanel.Close();
                        chessInfo.Close();
                        profitDescInfo.Close();
                        EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_PROBABILITY);
                    }
                    break;
            }
        }

        #endregion

        private void OnGUI()
        {
            if (GUI.Button(new Rect(200, 50, 50, 25), "翻车"))
            {
                AutoChessManager.Ins.cacheData.CurPlayerData.TestDelateOneHeroData();
            }
            //if (GUI.Button(new Rect(200, 200, 200, 200), "Cloud In"))
            //{
            //    LoadingPanel.Instance.ShowCloudMask();
            //}

            //if (GUI.Button(new Rect(200, 400, 200, 200), "Cloud Out"))
            //{
            //    if (LoadingPanel.Instance.IsCloudMaskShow())
            //    {
            //        LoadingPanel.Instance.HiedCloudMask();
            //    }
            //}

            //if (GUI.Button(new Rect(200, 600, 200, 200), "Delete All Cloud"))
            //{
            //    LoadingPanel.Instance.ClearAllCloudParticles();
            //}
        }
    }
}